const app = getApp();
const amap = app.data.amap;
const key = app.data.key;

Page({
  data: {
    longitude: '',
    latitude: '',
    isShow: false,
    detailStatus: false,
    searchlocation:"",
    status: '',
    markers: [],
    points: [],
    circles:[],
    distance: '',
    cost: '',
    address: {
      province:'',
      city:'',
      district:'',
      township:'',
      street:''
    },
    tips: {},
    polyline: []
  },
 onLoad() {
    this.getLocalCity();
  },
  onShow: function () {
    var that = this;
    that.setData({
      currentTab: 0 //当前页的一些初始数据
    })
    this.onLoad(); //重新加载onLoad()
  },
  async getLocalCity(){
   await new Promise((resolve, reject) => { wx.getLocation({
     type:"gcj02",
      success:res=> {
        if (res && res.longitude) {
          this.setData({
            longitude: res.longitude,
            latitude: res.latitude,
            points: [{
              longitude: res.longitude,
              latitude: res.latitude
            }], 
            circles: [{
              latitude: res.latitude,
              longitude: res.longitude,
              color: '#0bb3f1',
              fillColor: '#7cb5ec88',
              radius: 15,
              strokeWidth: 1
              }]
          })
        }
        resolve(res);  
      }
    })
  });
     wx.request({
    url: 'https://restapi.amap.com/v3/geocode/regeo?key=6d16dbafef3b0e70d20a593c046d8881&location='+this.data.longitude+','+this.data.latitude,
    header: { 
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  },
    success: (result) => {
     this.setData({
       address:{
         city:result.data.regeocode.addressComponent.city,
         district:result.data.regeocode.addressComponent.district,
         province:result.data.regeocode.addressComponent.province,
         township:result.data.regeocode.addressComponent.township,
         street:result.data.regeocode.addressComponent.streetNumber.street
       },
       markers: [{
        id: 0,
        titile:"我的位置",
        longitude: this.data.longitude,
        latitude: this.data.latitude,
        iconPath: '../../src/images/navi_s.png',
        width: 32,
        height: 32
      }]
     })
      this.getNeighborPark();
    },
  })
},
//获取附近的停车场
getNeighborPark(){
  var keywords =  this.data.address.province+this.data.address.city+this.data.address.district+this.data.address.township+this.data.address.street+"停车场";
  var myAmap = new amap.AMapWX({ key: key });
  myAmap.getInputtips({
    keywords: keywords,
    location: '',
    success: res=> {
      if (res && res.tips) {
       
        var markers= [{
          id: 0,
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          iconPath: '../../src/images/navi_s.png',
          titile:"我的位置",
          width: 32,
          height: 32
        }];
        for (let i = 0; i < res.tips.length; i++) {
          var neighbormark = {};  //先定义一个对象，然后再把下面请求回来的属性放进来
          var neighborpoint = {};
          neighbormark.id = i+1;
          neighbormark.title = res.tips[i].name;
          neighbormark.longitude = res.tips[i].location.split(',')[0];
          neighbormark.latitude = res.tips[i].location.split(',')[1];
          neighbormark.iconPath ='../../src/images/park.png';
          neighbormark.width = 32;
          neighbormark.height =32;
          neighborpoint.longitude = res.tips[i].location.split(',')[0];
          neighborpoint.latitude = res.tips[i].location.split(',')[1];
          markers.push(neighbormark);
          //this.data.points.push(neighborpoint);
        };
       
        this.setData({
          markers:markers
        })
      }
      
    },
  })
  // this.data.markers[0].on('click',this.markerclick)
  console.log(this.data.markers[0]);
},
markerTap(e) {
  //e.target.getExtData() 获取点击的marker属性 然后显示当前marker详情
 console.log(e);
 var parkid = e.detail.markerId;
 if (this.data.points.length > 1) {
  this.data.points.pop();
  this.setData({ polyline: [] });
};
var points = this.data.points;
points.push({
  longitude: this.data.markers[parkid].longitude,
  latitude:  this.data.markers[parkid].latitude
})
console.log(points);
this.setData({
  isShow: false,
  points: points,
  searchlocation:this.data.markers[parkid].title
})
this.goTo();
},
  bindInput: function (e) {
    var _this = this;
    var keywords =  this.data.address.province+this.data.address.city+this.data.address.district+e.detail.value+"停车场";
    var myAmap = new amap.AMapWX({ key: key });
    myAmap.getInputtips({
      keywords: keywords,
      location: '',
      success: function (res) {
         console.log(res);
        if (res && res.tips) {
          _this.setData({
            isShow: true,
            tips: res.tips
          });
        }
      }
    })
  },
  bindSearch: function (e) {
    console.log(e);
    var keywords = e.target.dataset.keywords;
    var location = e.target.dataset.location;    
    var id =  e.target.dataset.id;
    location = location.split(',');
    if (this.data.markers.length > 1 && this.data.points.length > 1) {
      this.data.markers.pop();
      this.data.points.pop();
      this.setData({ polyline: [] });
    }
    console.log(this.data.points);
    var markers = this.data.markers;
    var points = this.data.points;
    console.log(points);
    markers.push({
      id: id,
      title:keywords,
      longitude: location[0],
      latitude: location[1],
      iconPath: '../../src/images/navi_e.png',
      width: 32,
      height: 32
    });
    points.push({
      longitude: location[0],
      latitude: location[1]
    })
    console.log(points);
    this.setData({
      isShow: false,
      markers: markers,
      points: points,
      searchlocation:keywords
    })
    this.goTo();
  },
  //点击地图隐藏信息框
  hideshow(){
    this.setData({
      isShow:false,
      detailStatus:false
    })
  },
  goDetail(e){
      wx.openLocation({
        latitude:parseFloat(e.currentTarget.dataset.latitude),	//维度
        longitude: parseFloat(e.currentTarget.dataset.longitude), //经度
        name: e.currentTarget.dataset.address,	//目的地定位名称
        scale: 15,	//缩放比例
        address: e.currentTarget.dataset.address,	//导航详细地址
      })
  },
  goTo(e) {
    if (this.data.points.length < 2) {
      wx.showToast({ title: '请输入终点' })
      return;
    }
    var status;
    var car = 'car';
    if(e!=null){
     status = e.target.dataset.status;
    }else{
      status = car;
    }
    var myAmap = new amap.AMapWX({ key: key });
    switch (status) {
      case 'car':
        myAmap.getDrivingRoute(this.getDataObj());
        break;
      case 'walk':
        myAmap.getWalkingRoute(this.getDataObj());
        break;
      case 'ride':
        myAmap.getRidingRoute(this.getDataObj());
        break;
      default:
        return;
    }
    this.setData({
      detailStatus: true,
      status: status
    })
  },
  getDataObj(color) {
    var _this = this;
    var color = '#0091ff' ;
    return {
      origin: _this.data.points[0].longitude + ',' + _this.data.points[0].latitude,
      destination: _this.data.points[1].longitude + ',' + _this.data.points[1].latitude,
      success(data) {
        var points = [];
        if (!data.paths || !data.paths[0] || !data.paths[0].steps) {
          wx.showToast({ title: '失败！' });
          return;
        }
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          var steps = data.paths[0].steps;
          console.log("steps--->"+steps.length);
          var count=0;
          for (var i = 0; i < steps.length; i++) {
            var poLen = steps[i].polyline.split(';');
            count+=poLen.length;
            for (var j = 0; j < poLen.length; j++) {
              points.push({
                longitude: parseFloat(poLen[j].split(',')[0]),
                latitude: parseFloat(poLen[j].split(',')[1])
              })
            }
          }
          console.log("count-->"+count);
        }
        _this.setData({
          distance: data.paths[0].distance,
          cost: parseInt(data.paths[0].duration / 60),
          polyline: [{
            points: points,
            color: color,
            width: 6
          }]
        });
      },
      fail(info) {
        wx.showToast({ title: '失败！' })
      }
    }
  },
})

